package mo.leetcode_top;

import java.util.HashMap;
import java.util.Map;

public class L146_LRU {

    private static class Node {
        private int key;
        private int value;
        private Node pre;   //删除某个节点的时候需要找到pre节点
        private Node next;
        Node(){}
        Node(int key, int value){
            this.key = key;
            this.value = value;
        }
    }

    private Node dummyHead = new Node();
    private Node dummyTail = new Node();
    private int capacity;
    private int size;
    private Map<Integer, Node> nodeMap = new HashMap<>();

    public L146_LRU(int capacity) {
        this.capacity = capacity;
        this.size = 0;
        dummyHead.next = dummyTail;
        dummyTail.pre = dummyHead;
    }

    private void addNode(Node node) {
        Node originNex = dummyHead.next;
        dummyHead.next = node;
        node.pre = dummyHead;
        node.next = originNex;
        originNex.pre = node;
    }

    private void delNode(Node node) {
        Node pre = node.pre;
        Node nex = node.next;
        pre.next = nex;
        nex.pre = pre;
        node.pre = null;
        node.next = null;
    }

    public int get(int key) {
        Node node = nodeMap.get(key);
        if (node == null) {
            return -1;
        }
        delNode(node);
        addNode(node);
        return node.value;
    }

    public void put(int key, int value) {
        Node node = nodeMap.get(key);
        if (node != null) {
            node.value = value;
            delNode(node);
            addNode(node);
        } else {
            //先判断容量
            if (size < capacity) {
                size++;
            } else {
                Node delNode = dummyTail.pre;
                nodeMap.remove(delNode.key);
                delNode(delNode);
            }
            //插入节点
            node = new Node(key, value);
            addNode(node);
            nodeMap.put(key, node);
        }
    }


}
